<?php
namespace App\Http;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class TokenProxy
{
    protected $http;

    public function __construct(Client $http)
    {
        $this->http = $http;
    }

    public function login($email,$password)
    {
        $check = auth()->attempt(['email' => $email, 'password' => $password]);
        if ($check){
            return $this->proxy('password',[
                'username' => $email,
                'password' => $password
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => 'Credentials not match'
            ],421);
        }
    }

    public function logout()
    {
        $user = auth()->guard('api')->user();
        if(!$user){
            return response()->json([
                'status' => false,
                'message' => 'Authorization invild'
            ]);
        }
        $accessToken = $user->token();

        app('db')->table('oauth_refresh_tokens')
            ->where('access_token_id', $accessToken->id)
            ->update([
                'revoked' => true,
            ]);

        app('cookie')->forget('refreshToken');

        $accessToken->revoke();

        return response()->json([
            'message' => 'Logout!'
        ],204);
    }

    public function refresh()
    {
        $refreshToken = request()->cookie('refreshToken');

        return $this->proxy('refresh_token',[
            'refresh_token' => $refreshToken
        ]);
    }

    public function proxy($grantType, array $data = [])
    {
        $data = array_merge($data, [
            'client_id' => env('OAUTH_CLIENT_ID'),
            'client_secret' => env('OAUTH_CLIENT_SECRET'),
            'grant_type' => $grantType,
            'scope' => '',
        ]);

//        try {
            $response = $this->http->post(env('APP_URL').'/oauth/token', [
                'form_params' => $data
            ]);
//        } catch (RequestException $exception) {
//            abort(401, '请求失败，服务器错误');
//        }


        $token = json_decode((string) $response->getBody(), true);

        return response()->json([
            'token' => $token['access_token'],
            'expires_in' => $token['expires_in']
        ])->cookie('refreshToken', $token['refresh_token'],14400,null,null,false,true);
    }
}